import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

const String h5JS2FlutterByUrl = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>通过URL向flutter传递参数</title>
</head>
<body>
    <button id="btn">传递参数</button>
    <script type="text/javascript">
      var btn = document.getElementById('btn');
      btn.addEventListener('click', function() {
          document.location="hi://webview?name=zsl";
      });
    </script>
</body>
</html>
''';

// JS向Flutter传递数据-通过URL方式
class Js2flutterByUrl extends StatefulWidget {
  const Js2flutterByUrl({super.key});

  @override
  State<Js2flutterByUrl> createState() => _Js2flutterByUrlState();
}

class _Js2flutterByUrlState extends State<Js2flutterByUrl> {
  late WebViewController controller;

  get _loadBtn => FilledButton(
    onPressed: () {
      // 加载H5
      controller.loadHtmlString(h5JS2FlutterByUrl);
    },
    child: Text('加载H5', style: TextStyle(color: Colors.white)),
  );

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      // 开启JS执行
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onNavigationRequest: (NavigationRequest request) {
            // 约定一个通信协议 hi://webview
            if (request.url.startsWith('hi://webview')) {
              debugPrint('JS向Flutter传递数据-通过URL方式: $request');
              Uri uri = Uri.parse(request.url);
              // 解析数据
              var name = uri.queryParameters['name'];
              debugPrint('name: $name');
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(SnackBar(content: Text('name: $name')));
              return NavigationDecision.prevent;
            }
            debugPrint('非hi://webview开头的URL,则放行 $request');
            return NavigationDecision.navigate;
          },
        ),
      );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('JS向flutter传递数据'), actions: [_loadBtn]),
      body: WebViewWidget(controller: controller),
    );
  }
}
